'''
Copyright: 
Descripttion: 画 提子曲线
version: 
Author: chengx
Date: 2022-03-11 10:51:58
LastEditors: chengx
LastEditTime: 2022-03-13 12:39:32
'''
import os
import numpy as np
from PIL import Image
import matplotlib.pyplot as plt
import matplotlib.patches as mpathes
font1 = {'family': 'Times New Roman',
'size': 24,
}
import scipy.signal
plt.rcParams['font.sans-serif'] = ['SimHei']  # 用来正常显示中文标签
plt.rcParams['axes.unicode_minus'] = False  # 用来正常显示负号


def drawGrapeSpectral(filePath):#画一个提子上某区域的全部近红外光谱，并高亮其平均线
    data = np.memmap(filePath,dtype=np.float16,mode='r').copy()
    data = data.reshape(640,224,640)

    c = data[265:275,:,430:440]

    m = data[220:320,50,385:485].reshape(-1)# 整幅图有十几颗提子，只取了其中一颗
    min = m.min()
    max = m.max()
    fm = max-min
    print(fm,max,min)
    for i in range(m.shape[0]):
        m[i] = float(m[i]-min)/fm*255
    m = m.reshape(100,100).astype(np.uint8)

    # plt.imshow(m,cmap='gray')
    # plt.show()
    c = c.reshape(10,-1,10)
    c = c.transpose(0,2,1)
    print(c.shape)
    c = c.reshape(-1,224)
    avg = np.mean(c,axis=0)
    c = c.transpose(1,0)

    fig=plt.figure()
    left,bottom,width,height=0.1,0.1,0.8,0.8
    ax1=fig.add_axes([left,bottom,width,height])    # 设置figure的比例大小
    ax1.plot(c,'gray')
    ax1.plot(avg,'r')
    ax1.set_xlabel("Wavelength/nm",font1)
    ax1.set_ylabel(r"Absorbance",font1)
    plt.tick_params(labelsize=22)# 设置坐标轴的字体大小
    plt.xticks([0,56,112,168,224],[900,1100,1300,1500,1700])


    left,bottom,width,height=0.6,0.6,0.25,0.25
    ax2=fig.add_axes([left,bottom,width,height])    # 设置ax2的位置以及大小
    ax2.imshow(m,cmap='gray')
    xy2 = np.array([40,40])
    rect = mpathes.Rectangle(xy2,20,20,fill = False,linewidth=2)#,color='r'
    ax2.add_patch(rect)
    plt.plot()
    plt.yticks([])
    plt.xticks([])
    plt.show()

def draw():# 画提子一条曲线和求导曲线
    a = np.load('./cut/grape/data.npy')
    print(a.shape)
    plt.plot(a[0,:].reshape(-1),color='black')
    plt.xticks([0,56,112,168,224],[900,1100,1300,1500,1700])
    plt.tick_params(labelsize=22)# 设置坐标轴的字体大小
    plt.xlabel(r"Wavelength /nm",font1)
    plt.title(r"原始光谱",size=22)
    plt.ylabel(r"Absorbance",font1)

    plt.show()

    b =  scipy.signal.savgol_filter(a, 9, 2, deriv=1)
    m = b[0,:].reshape(-1)
    m = m*100
    plt.plot(m,color='black')
    plt.xticks([0,56,112,168,224],[900,1100,1300,1500,1700])
    plt.tick_params(labelsize=22)# 设置坐标轴的字体大小
    plt.xlabel(r"Wavelength /nm",font1)
    plt.title(r"SG处理后曲线",size=22)
    plt.ylabel(r"1nd Derivative",font1)
    plt.show()
    


if __name__ == '__main__':
    # draw()
    drawGrapeSpectral('./cut/grape/grape.raw')
    #grape.raw文件较大无法上传，大概是一个640*224*640的图，分别为宽，波段，高，也
    #是提子的高光谱图像